package cn.yuanqiao.archive.wenjianzhengli.service.impl;

import cn.yuanqiao.archive.appManager.domain.DataScopeBase;
import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantSysDictData;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.wenjianzhengli.mapper.DaiguidangMapper;
import cn.yuanqiao.archive.wenjianzhengli.service.DaiguidangService;
import cn.yuanqiao.common.utils.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : 庸人一个
 * @create : 2024/4/11 10:00
 */
@Service
@SuppressWarnings("all")
public class DaiguidangServiceImpl implements DaiguidangService {

    @Autowired
    private ITenantSysDictTypeService tenantSysDictTypeService;

    @Autowired
    private ITenantCateMdataListService tenantMdataListService;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    @Autowired
    private DaiguidangMapper daiguidangMapper;
    @Override
    public Map<String, Object> getExportTitleAndBody(JSONObject json, List<Map<String, String>> getexportfield) {
        Map<String, Object> map = new HashMap<>();
        //String ids = json.getString("ids");  //选中数据的id
        //String state = json.getString("state");  //数据状态
        String categoryId = json.getString("categoryId");
        TenantCategory tenantCategoryTable = new TenantCategory();
        //TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategoryTable.getTableName());
        ArrayList<String> titles = new ArrayList<>();
        Map<String, Map<String,String>> stringObjectHashMap = new HashMap<>();
        StringBuffer selectColumns = new StringBuffer();
        Iterator<Map<String, String>> iterator = getexportfield.iterator();
        while (iterator.hasNext()){
            Map<String, String> next = iterator.next();
            String field_name = next.get("FIELD_NAME");
            String field_caption = next.get("FIELD_CAPTION");
            String export_column_name = next.get("EXPORT_COLUMN_NAME");
            String showType = String.valueOf(next.get("SHOWTYPE"));
            String finalName = "";
            if(StringUtils.isNotEmpty(export_column_name)) {
                titles.add(export_column_name);
                finalName = export_column_name;
            } else {
                titles.add(field_caption);
                finalName = field_caption;
            }
            if("5".equals(showType)){
                List<TenantSysDictData> tenantSysDictData = tenantSysDictTypeService.selectDictDataByType(field_name);
                if(null!=tenantSysDictData){
                    Map<String, String> map2 = new HashMap<>();
                    for(int i=0;i<tenantSysDictData.size();i++){
                        TenantSysDictData tenantSysDictData1 = tenantSysDictData.get(i);
                        String lb = tenantSysDictData1.getDictLabel();
                        String va = tenantSysDictData1.getDictValue();
                        map2.put(va,lb);
                    }
                    stringObjectHashMap.put(finalName,map2);
                }
            }
            selectColumns.append(field_name).append(",");
        }
        String selectColumnStr = selectColumns.deleteCharAt(selectColumns.length()-1).toString();
        List<List<String>> bodyList = new ArrayList<>();
        //List<Map<String, Object>> list = queryListOfWjzl(json, selectColumnStr, tenantCategory);
        json.put("fields",selectColumnStr);
        List<Map<String, Object>> list = getlistbytreenode(json);
        String[] columnArr = selectColumnStr.toUpperCase().split(",");
        Iterator<Map<String, Object>> iterator1 = list.iterator();
        while (iterator1.hasNext()){
            List<String> valsList = new ArrayList<>();
            Map<String, Object> next = iterator1.next();
            for(String s:columnArr){
                valsList.add(String.valueOf(next.get(s)));
            }
            bodyList.add(valsList);
        }
        map.put("title",titles);
        map.put("body",bodyList);
        map.put("dict",stringObjectHashMap);
        return map;
    }

    private List<Map<String, Object>> getlistbytreenode(JSONObject json) {
        Long categoryId = json.getLong("categoryId");//门类id
        Long menuId = json.getLong("menuId");//菜单id
        String subTableName = StringUtils.isEmpty(json.getString("subTableName")) ?
                json.getString("sub_table_name") :
                json.getString("subTableName");//层级节点的表名
        JSONArray propertyName = json.getJSONArray("propertyName");//分类节点的属性
        JSONArray propertyValue = json.getJSONArray("propertyValue");//分类节点的值
        //Long fondsId=json.getLong("fondsId");//全宗id
        Integer state=json.getInteger("state");//状态
        Integer jsType = null;
        if(json.containsKey("jsType") && StringUtils.isNotEmpty(json.getString("jsType"))){
            jsType = json.getInteger("jsType");
        }

        String fields="ID,"+json.getString("fields");//需要查询的字段
        JSONArray jsonArray = json.getJSONArray("searchcolumn");//查询条件
        StringBuilder sb=new StringBuilder(" and ");//用于拼接条件
        String orderstr=json.getString("order");//用于排序
        String ids=json.getString("ids");//用于排序
        int type=-1;
        /**处理查询条件*/
        if(null==jsonArray){
            jsonArray=new JSONArray();
        }
        if(jsonArray.size()>0){
            concatQueryCondition(jsonArray,sb);
        }
        /**处理表名*/
        TenantCategory category=new TenantCategory();
        String tablename="";
        if (null!=subTableName&&!"".equals(subTableName)) {//有层级信息
            tablename=subTableName;
            String tablenametype=subTableName.substring(subTableName.length()-3,subTableName.length()-2);
            if("F".equalsIgnoreCase(tablenametype)){//档案层
                type=0;
            }else if("V".equalsIgnoreCase(tablenametype)){//案卷层
                type=1;
            }else if("X".equalsIgnoreCase(tablenametype)){//项目层
                type=3;
            }else if("E".equalsIgnoreCase(tablenametype)){//电子文件层
                type=2;
            }
        }else{
            TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, category.getTableName());
            if (tenantCategory.getType()==0){//件
                tablename=tenantCategory.getFileTableName();
            }else if(tenantCategory.getType()==1){//卷
                tablename=tenantCategory.getFolderTableName();
            }else if(tenantCategory.getType()==2){//电子文件
                tablename=tenantCategory.getEfileTableName();
            }else if(tenantCategory.getType()==3){//项目
                tablename=tenantCategory.getItemTableName();
            }
            type=tenantCategory.getType();
        }
        /**处理分类值*/
        if(propertyName.size()>0){
            for (int i = 0; i < propertyName.size(); i++) {
                sb.append(" "+propertyName.get(i)+" = "+"'"+propertyValue.get(i)+"' and ");
            }
        }
        String tiaojian=sb.toString();
        if(StringUtils.isNotEmpty(ids)){   //id不为空时拼上id
            if(tiaojian.endsWith("and ") || tiaojian.endsWith("and")) tiaojian+=" id in ("+ids+") ";
            else tiaojian+=" and id in ("+ids+") ";
        }
        /**处理拼接条件时的sql*/
        if (tiaojian.endsWith("and ")){
            tiaojian=tiaojian.substring(0,tiaojian.length()-4);
        }else if(tiaojian.endsWith("and")){
            tiaojian=tiaojian.substring(0,tiaojian.length()-3);
        }
        /**处理排序*/
        if(null!=orderstr&&!"".equals(orderstr)){
            orderstr=" order by "+orderstr;
        }else{
            String applyorderstr=tenantMdataListService.getorder(categoryId, menuId, type);
            if(null!=applyorderstr&&!"".equals(applyorderstr)){
                orderstr=" order by "+applyorderstr;
            }
        }
//        PageUtils.startPage();
        /**查询列表并返回*/
        return daiguidangMapper.getlistbytreenode(new DataScopeBase(menuId),fields,tablename,state,jsType,tiaojian,orderstr);
    }


    public void concatQueryCondition(JSONArray searchCondition,StringBuilder queryCondition){
        //拼接前端查询条件
        if (searchCondition!=null && searchCondition.size()>0 ) {
            String queryType = null;		//查询类型
            String showType = null;		//展示类型
            String fieldName = null;		//展示类型
            String[] queryValue = new String[2];		//查询值
            for (int j = 0; j < searchCondition.size(); j++) {
                JSONObject jsonObject = searchCondition.getJSONObject(j);
                queryType = jsonObject.getString("queryType"); //根据查询项获取对应的查询类型
                showType = jsonObject.getString("showType"); //根据查询项获取对应的展示类型
                fieldName = jsonObject.getString("column");
                if ("4".equals(queryType)) {	//区间查询会有2个值
                    queryValue[0] = jsonObject.getString("value");		//根据查询项获取对应的查询值
                    queryValue[1] = jsonObject.getString("valueTwo");
                }else{
                    queryValue[0] = jsonObject.getString("value");		//根据查询项获取对应的查询值
                }
                //logger.debug("queryColumns["+j+"] = "+queryColumns[j]+"--"+queryValue[0]);
                queryCondition.append(getQueryCriteriaByType(fieldName,showType,queryType,queryValue));
            }
        }
    }

    /**
     * <p>Title: getQueryCriteriaByType</p>
     * <p>Description: 根据传入的类型type 组合查询条件</p>
     * @param column 列名
     * @param showType 查询类型
     * 		0	不参加查询	暂不考虑;
     * 		1	精确查询		= '匹配值';
     * 		2	模糊查询		like '%匹配值%';
     * 		3	左匹配查询	like '匹配值%';
     * 		4	区间查询		'匹配值1'<列<'匹配值2'	?是否包含=;
     * 		5	列表查询		不做处理;
     * 		6	单选对话框	不做处理;
     * 		7	多选对话框	不做处理;
     * 		8	多词检索		分词 以空格为标志;
     * @param values 查询值
     * @return
     */
    public String getQueryCriteriaByType(String column,String showType,String queryType,String[] values){
        String criteria = " ";
        Integer type = Integer.parseInt(queryType);
        if(8!=type||4!=type){
            if("".equals(values[0])||null==values[0]){
                return "";
            }
        }
        for(int i=0;i<values.length;i++){
            if(StringUtils.isNotEmpty(values[i])){
                values[i] = values[i].trim();
            }
        }
        switch (type) {
            case 0: //不参加查询	暂不考虑;
                criteria = " ";
                break;
            case 1: //精确查询	= '匹配值';
                criteria += column + " = '" + values[0].replace("'","&apos;") + "' and";
                break;
            case 2: //模糊查询	like '%匹配值%';
                criteria += column + " like '%" + values[0].replace("'","&apos;") + "%' and";
                break;
            case 3: //左匹配查询	like '匹配值%';
                criteria += column + " like '" + values[0].replace("'","&apos;") + "%' and";
                break;
            case 4: //区间查询	'匹配值1'<=列<='匹配值2'
                if(StringUtils.isNotEmpty(values[0])) {
                    criteria += "'"+ values[0] + "' <= " + column + " and";
                }
                if(StringUtils.isNotEmpty(values[1])) {
                    criteria += " " + column + " <= '" + values[1] + "' and" ;
                }
                break;
            case 5: //列表查询	不做处理;
                criteria = " ";
                break;
            case 6: //单选对话框	不做处理;
                criteria = " ";
                break;
            case 7: //多选对话框	不做处理;
                criteria = " ";
                break;
            case 8: //多词检索	分词 以空格为标志;	多词检索中 如果有查询列里的值存在空格 怎么处理 (查询时使用""将带空格需要整体查询的值标记 , 例如:"A B")
                String[] value = values[0].split(" ");
                criteria += "(";
                for (int i = 0; i < value.length; i++) {
                    if (i==0) {
                        criteria += column + " like '%" + value[i].replace("'","&apos;") + "%'";
                    }else{
                        criteria += " or "+column + " like '%" + value[i].replace("'","&apos;") + "%'";
                    }
                }
                criteria += ") and";
                break;
            default:
                break;
        }
        return criteria;
    }
}
